package com.bigfans.catalogservice.api;

import com.bigfans.catalogservice.api.request.ProductCreateRequest;
import com.bigfans.catalogservice.service.product.ProductService;
import com.bigfans.catalogservice.service.productgroup.ProductGroupService;
import com.bigfans.framework.plugins.UploadResult;
import com.bigfans.framework.web.BaseController;
import com.bigfans.framework.web.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
public class ProductManageApi extends BaseController {

    @Autowired
    private ProductService productService;
    @Autowired
    private ProductGroupService productGroupService;

    @PostMapping(value = "/itemservice")
    public RestResponse create(@RequestBody ProductCreateRequest request) throws Exception{
        productGroupService.create(request.getProductGroup(), request.getProducts(), request.getAttributes() , request.getTags());
        return RestResponse.ok();
    }

    @PostMapping(value = "/itemservice/uploadImg")
    public RestResponse uploadImg(@RequestParam("file") MultipartFile image) throws Exception {
        String ext = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.') + 1);
        UploadResult uploadResult = productService.uploadImage(image.getInputStream(), ext);
        Map<String , Object> data = new HashMap<>();
        data.put("storageType", uploadResult.getStorageType());
        data.put("filePath", uploadResult.getFilePath());
        data.put("fileKey", uploadResult.getFileKey());
        return RestResponse.ok(data);
    }

    @PostMapping(value = "/itemservice/removeImg")
    public RestResponse removeImg(@RequestBody Map<String, Object> params) throws Exception {
        UploadResult uploadResult = productService.removeImage((String) params.get("file"));
        RestResponse resp = new RestResponse();
        if (!uploadResult.isSuccess()) {
            resp.setStatus(404);
            resp.setMessage("删除图片失败");
        }
        return resp;
    }

}
